﻿using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Demo.Public.Base
{
    public class BindableBase : INotifyPropertyChanged
    {
        // PropertyChanged事件用于通知监听者某个属性值已更改
        public event PropertyChangedEventHandler? PropertyChanged;

        /// <summary>
        /// 设置属性值，并在值改变时引发PropertyChanged事件
        /// </summary>
        /// <param name="field">要设置的属性的引用</param>
        /// <param name="value">要设置的新值</param>
        /// <param name="propertyName">属性名称，默认使用调用者成员名称属性</param>
        /// <typeparam name="T">属性的类型</typeparam>
        public void RaisePropertyChanged<T>(ref T field, T value, [CallerMemberName] string propertyName = "")
        {
            // 检查新旧值是否相等，如果不相等则更新属性值并引发事件
            if (!EqualityComparer<T>.Default.Equals(field, value))
            {
                field = value;
                RaisePropertyChanged(propertyName);
            }
        }

        /// <summary>
        /// 引发PropertyChanged事件
        /// </summary>
        /// <param name="propertyName">更改的属性名称</param>
        protected void RaisePropertyChanged(string propertyName)
        {
            // 引发PropertyChanged事件，通知监听者指定属性值已更改
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}